<template>
	<view class="body">
		<image class="log" src="../../static/pic/banner1.png" mode=""></image>
		<view class="container">
			<input class="input" placeholder="请输入账号" type="text" @input="getUsername" />
			<input class="input" placeholder="请输入密码" type="password" @input="getPassWord" />
			<text class="to-register" @click="toregister">去注册</text>
			<button class="loginbtn" type="primary" @click="submit">登陆</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		http
	} from '../../API/request.js';
	import {
		onLoad,
		onShow,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	const username = ref('')
	const password = ref('')
	const openid = ref('')
	const params = ref({
		username,
		password
	})
	const getUsername = (e) => {
		username.value = e.detail.value.trim()
	}
	const getPassWord = (e) => {
		password.value = e.detail.value.trim()
	}
	const submit = () => {
		if (!username.value || !password.value) {
			uni.showToast({
				title: '存在未填项',
				icon: 'none'
			})
			return
		}
		http.post('/toLogin', {
			username: username.value,
			password: password.value,
		}).then((res) => {
			const {
				data
			} = res
			if (data === 'pwdError') {
				uni.showToast({
					title: '密码错误',
					icon: 'none'
				})
				return
			} else if (data === 'error') {
				uni.showToast({
					title: '账号信息不存在',
					icon: 'none'
				})
			} else if (data === 'success') {
				uni.showToast({
					title: '登陆成功',
					icon: 'none'
				})
				uni.setStorageSync('login_account', true)
				uni.setStorageSync('account', params)
				uni.redirectTo({
					url: '/pages/home/home'
				})
			}
		})
	}
	const toregister = () => {
		uni.redirectTo({
			url: '/subpkg/register/register'
		})
	}
	onLoad(() => {
		if (uni.getStorageSync('login_account')) {
			uni.switchTab({
				url: '/pages/home/home'
			})
		} else {
			openid.value = uni.getStorageSync('openid')
			if (!openid) {
				uni.login({
					success: function(res) {
						if (res.code) {
							http.get('/login', {
								params: {
									code: res.code
								}
							}).then((res) => {
								const {
									data
								} = res
								if (data !== "error") {
									uni.setStorageSync('openid', data)
								}
							})
						}
					}
				})
			}
		}
	})
</script>

<style lang="less">
	.body {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 100rpx;
		height: 100vh;
		background-color: #fff;

		.log {
			width: 150rpx;
			height: 150rpx;
			border-radius: 50%;
		}

		.container {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-top: 100rpx;
			width: 70%;

			.input {
				width: 100%;
				border-bottom: 2rpx solid #aaa;
				margin-bottom: 40rpx;
			}

			.to-register {
				margin-right: auto;
				color: skyblue;

			}

			.loginbtn {
				width: 80% !important;
				margin-top: 80rpx;
			}
		}

	}
</style>